﻿using DAL.Entity;
using DAL.Persistencia;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace NewTierra.Pages.Operacoes
{
    public partial class AddFoto : System.Web.UI.Page
    {
        public int File_ServExtraID
        {
            get
            {
                try
                {
                    if ((Session["fseID"] == null) || (Session["fseID"].ToString() == ""))
                        return 0;
                    else return Convert.ToInt32(Session["fseID"].ToString());
                }
                catch (Exception)
                {
                    return 0;
                }
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            //fupFile_ServExtra_Foto.Attributes.Add("OnClick", "javascript:document.forms[0].encoding = \"multipart/form-data\";");
        }

        protected void btnEnviar_Click(object sender, EventArgs e)
        {
            if (File_ServExtraID != 0)
            {
                HttpFileCollection hfc = Request.Files;

                if (hfc.Count > 0)
                {
                    File_ServExtra_Foto fsef = new File_ServExtra_Foto();

                    if ((fupFile_ServExtra_Foto.FileName.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase)) ||
                        (fupFile_ServExtra_Foto.FileName.EndsWith(".jpeg", StringComparison.OrdinalIgnoreCase)) ||
                        (fupFile_ServExtra_Foto.FileName.EndsWith(".png", StringComparison.OrdinalIgnoreCase)))
                    {
                        HttpPostedFile hpf = hfc[0];

                        if (hpf.ContentLength > 0)
                        {
                            string foto = Convert.ToString(Guid.NewGuid().ToString("n") + System.IO.Path.GetExtension(fupFile_ServExtra_Foto.FileName));
                            hpf.SaveAs(Server.MapPath("~/Galeria/ServExtra/" + foto));

                            File_ServExtra_FotoDAL fsefd = new File_ServExtra_FotoDAL();
                            fsef.fsef_nome = foto;
                            fsef.fsef_File_ServExtra_ID = File_ServExtraID;
                            fsefd.Adicionar(fsef);
                        }
                    }
                    else
                    {
                        throw new Exception("Erro. Selecione apenas imagens jpg ou png.");
                    }
                }

                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "a", 
                    "alert('Foto adicionada com sucesso!'); window.close()", true);
            }
            else
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "a", 
                    "alert('O file extra não foi encontrado! Favor tentar novamente'); window.close()", true);
        }
    }
}